﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Xml.Linq;

namespace Leuphana.GuidedTour.App
{
    public class TourDataLoader
    {
        #region Singleton

        private static TourDataLoader _instance;

        // Singleton access
        public static TourDataLoader Current
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new TourDataLoader();
                }

                return _instance;
            }
        }

        #endregion

        private XDocument _data;

        protected TourDataLoader()
        {
            // Read the XML File
            var streamInto = Application.GetResourceStream(new Uri("Data/TourData.xml", UriKind.Relative));
            var streamReader = new StreamReader(streamInto.Stream);

            // Store in current instance
            _data = XDocument.Parse(streamReader.ReadToEnd());

            streamReader.Close();
        }

        public List<XElement> LoadHotSpots()
        {
            // Return all hotspots
            var test1 = _data.Root.Elements().ToList();


            return _data.Root.Elements("HotSpot").ToList();
        }

        public XElement LoadHotSpot(string id)
        {
            // Get hotspot from xml
            var hotspot = _data.Root.Elements("HotSpot").First(h => h.Attribute("ID").Value == id);

            // If no hotspot was found...
            if (hotspot == null)
                throw new KeyNotFoundException("HotSpot not found");

            return hotspot;
        }

        public List<XElement> LoadArticles(string parentId)
        {
            // Get parent HotSpot
            var hotspot = _data.Root.Elements("HotSpot").FirstOrDefault(a => a.Attribute("ID").Value == parentId);

            // If parent was not found...
            if (hotspot == null)
                throw new KeyNotFoundException("HotSpot not found");

            // Get articles
            var articles = hotspot.Element("Articles").Elements("Article").ToList();

            // Return articles as list
            return articles;
        }

        public XElement LoadArticle(string id)
        {
            // Get article from xml
            var article = _data.Root.Descendants("Article").First(a => a.Attribute("ID").Value == id);

            // If no article was found...
            if (article == null)
                throw new KeyNotFoundException("Article not found");

            return article;
        }
    }
}
